package trefliq.EJB.sessionbeans;

import java.util.List;
import javax.annotation.security.PermitAll;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import trefliq.EJB.entities.OrdersItem;

/**
 *
 * @author eric
 */

@Stateless
@LocalBean
@PermitAll
public class OrdersItemSession {

    @PersistenceContext(unitName="trefliqPU")
    private EntityManager em;
    
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN, SecurityRole.EMPLOYEE})
    public List<OrdersItem> getAllOrdersItems() {
        return em.createNamedQuery("findAllOrdersItems", OrdersItem.class).getResultList();
    }
    
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN, SecurityRole.EMPLOYEE})
    public OrdersItem findOrdersItemById(Long ordersitemid) {
        return em.createNamedQuery("findOrdersItemById", OrdersItem.class).
                    setParameter("ordersitemid", ordersitemid).getSingleResult();
    }
    
    public OrdersItem deleteOrdersItem(OrdersItem ordersitem) {
        
        em.remove(em.merge(ordersitem));
        return ordersitem;
    }
    
    public OrdersItem editOrdersItem(OrdersItem ordersitem) {
        
        em.merge(ordersitem);
        return ordersitem;
    }
    
    public OrdersItem createOrdersItem(OrdersItem ordersitem) {

        em.persist(ordersitem);
        return ordersitem;
    }
    
    // DB helper methods
    
    //TODOSEC: @RolesAllowed({SecurityRole.ADMIN, SecurityRole.EMPLOYEE})
    public void deleteAll() {
        Query q = em.createQuery("DELETE FROM OrdersItem o");
        q.executeUpdate();
    }
}
